require('dotenv').config(); 
//越过浏览器CORS限制，端口转发

const express = require('express');
const multer = require('multer');
const axios = require('axios');
const cors = require('cors');
const fs = require('fs');

const app = express();
const upload = multer({ dest: 'uploads/' });

app.use(cors()); // 允许所有跨域

// 上传接口
app.post('/proxy-upload', upload.single('file'), async (req, res) => {
  try {
    // 读取本地上传的文件
    const filePath = req.file.path;
    const fileStream = fs.createReadStream(filePath);

    // 构造 formData
    const FormData = require('form-data');
    const form = new FormData();
    form.append('file', fileStream, req.file.originalname);

    // 这里可以加 strategy_id，如果需要
    // form.append('strategy_id', 1);

    // 发送到 lskypro 图床
      // 脱敏处理后的代码
    const response = await axios.post(process.env.UPLOAD_API_URL, form, {
      headers: {
        ...form.getHeaders(),
        Authorization: `Bearer ${process.env.UPLOAD_API_TOKEN}`,
        Accept: 'application/json'
      },
      // 跳过自签名证书校验
      httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false })
    });
    // const response = await axios.post('https://111.230.111.196:8080/api/v1/upload', form, {
    //   headers: {
    //     ...form.getHeaders(),
    //     Authorization: 'Bearer 1|1uRrzuZqGPmalOXM6NV1zg8e429lZqGYY5ItO3ff',
    //     Accept: 'application/json'
    //   },
    //   // 跳过自签名证书校验
    //   httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false })
    // });

    // 删除本地临时文件
    fs.unlinkSync(filePath);

    // 返回图床响应
    res.json(response.data);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: '上传失败', error: err.toString() });
  }
});

const PORT = 3001;
app.listen(PORT, () => {
  console.log(`CORS中转服务已启动，端口：${PORT}`);
});